#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, re, optparse, time


exp = re.compile("\/\*.*?\*\/", re.DOTALL)
fm = re.compile(".*?\.(cpp|hpp)")
v_dict = { 'DATE':lambda: time.ctime(),  }

def replace_variables(string, var_dict):
    s = string
    for old, new in var_dict.items():
        s = s.replace("$(" + old + ")", new())
    return s

def replace_comment(text, comment):
    m = exp.subn(comment, text, 1)
    return m[0]

def read_file(ifile):
    f = open(ifile)
    s = f.read()
    f.close()
    return s

def replace_comment_cb(file_name, comment, var_dict):
    old_content = read_file(file_name)
    o = open(file_name, "w")
    new_comment = replace_variables(comment, var_dict)
    o.write(replace_comment(old_content, new_comment))
    o.close()

def delete_comment_cb(file_name):
    old_content = read_file(file_name)
    o = open(file_name, "w")
    o.write(replace_comment(old_content, "").lstrip())
    o.close()

def add_comment_cb(file_name, comment):
    old_content = read_file(file_name)
    o = open(file_name, "w")
    o.write(comment.lstrip() + "\n" + old_content)
    o.close()

def process_dir(directory, file_callback, file_matcher, verbose):
    for root, dirs, files in os.walk(directory):
        for f in files:
            fname = os.path.join(root, f)
            if file_matcher.match(fname):
                if verbose:
                    print "Processing file:", fname
                file_callback(fname)

# fixhdr -m repl -t header.txt ../cpp_source_dir
# ./fixhdr.py -m repl -t ../gi/gimrt/doc/header.txt ../gi/gimrt/src/

p = optparse.OptionParser()
p.add_option("-m", "--method")
p.add_option("-t", "--template")
(opts, args) = p.parse_args()

#print dir(opts)
#print args

if len(args) != 1:
    p.error("directory required")
    
directory = args[0]

if opts.method == "del":
    fcb = lambda (fname): delete_comment_cb(fname)
elif opts.method == "add":
    if not opts.template:
        p.error("template file missing.")
    comment_file = read_file(opts.template).strip()
    fcb = lambda (fname): add_comment_cb(fname, comment_file)
elif opts.method == "repl":
    if not opts.template:
        p.error("template file missing.")
    comment_file = read_file(opts.template).strip()
    fcb = lambda (fname): replace_comment_cb(fname, comment_file, v_dict)
else:
    p.error("unknown method for -m: " + opts.method)

process_dir(directory, fcb, fm, True)
